<template>
   <div>
      <!-- 搜索添加 -->
      <div>
         <el-input size="" class="input-length" placeholder="请输入管理员名称" v-model="list.username" />
         <el-button type="primary" :icon="Search" @click="handSearch">查找</el-button>
         <el-button type="primary" :icon="Plus" @click="add">添加</el-button>

      </div>
      <!-- 创建、修改弹窗 -->
      <el-dialog v-model="dialogFormVisible" :title="bool ? '创建' : '编辑'" width='40%' destroy-on-close>
         <el-form :model="form.data" :rules="rules" ref="ruleFormRef">
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="username" >
               <el-input v-model="form.data.username" autocomplete="off" :disabled="bool==false"/>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth" prop="password" v-if="bool == true">
               <el-input v-model="form.data.password" autocomplete="off" type="password" />
            </el-form-item>
            <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
               <el-input v-model="form.data.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="真实姓名" :label-width="formLabelWidth" prop="realname">
               <el-input v-model="form.data.realname" autocomplete="off" />
            </el-form-item>

            <el-form-item label="角色" prop="roleIds" :label-width="formLabelWidth" :rules="bool==false?[{ required: true,message:'角色不能为空',trigger:'blur'}]:[]">
               <el-select multiple placeholder="请输入角色名称" style="width: 240px" v-model="form.data.roleIds">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
               </el-select>
            </el-form-item>
         </el-form>
         <template #footer>
            <span class="dialog-footer">
               <el-button type="primary" @click="handleToggleConfirm(ruleFormRef)">{{ bool==true?'增加':'修改' }}</el-button>
               <el-button  @click="ruset(ruleFormRef)"> 重置</el-button>
            </span>
         </template>
      </el-dialog>
      <!-- 渲染列表 -->
      <el-table :data="tableData" border style="width: 100%;margin-top: 20px;">
         <el-table-column prop="id" label="管理员ID"  align="center" />
         <el-table-column prop="username" label="管理员名称"  align="center" />
         <el-table-column prop="realname" label="真实姓名" align="center" />
         <el-table-column prop="phone" label="电话"  align="center" />
         <el-table-column prop="" label="管理员角色"  align="center">
            <template #default="scope">
               <div v-for="item in scope.row.roleIds"><el-tag>{{ handlerole(item) }}</el-tag></div>
            </template>
         </el-table-column>
         <el-table-column prop="" label="操作" align="center" >
            <template #default="scope">
               <div>
                  <el-button size="small" type="primary" @click="handleUpdata(scope.$index, scope.row)">修改</el-button>
                  <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row.id)">删除</el-button>
               </div>
            </template>
         </el-table-column>
      </el-table>
      <Pagings v-bind="pagination" @emitfather="CurrentList"></Pagings>
   </div>
</template>
<script setup lang="ts">
import { Plus, Search } from '@element-plus/icons-vue'
import { ref, onMounted, reactive } from 'vue'
import Pagings from '@/components/paging/Pagings.vue'
import { classPagination,ClassAdminUser } from '#/index'
import { post, get } from '@/utlis/http'
import { ElMessage,ElMessageBox, type FormInstance } from 'element-plus';
const tableData = ref([])
const pagination = reactive(new classPagination())
const list = ref<AdminType>({//请求管理员渲染列表
   _gp: 'admin',
   _mt: 'list',
   username: '',
   page: 1,
   limit: 10
})
// 渲染列表
function init() {
   get(list.value).then(res => {
      let { items, total } = res.data
      console.log(res);
      if (200 == res.errno) {
         if (items.length==0) {
            ElMessage.error('没有查找到')
         } else {
            tableData.value = items
            pagination.total = total
            ElMessage.success(res.errmsg)
         }
      } else {
         ElMessage.error(res.errmsg)
      }

   })
}
// 获得角色权限
let options:TypeUserRoleoption[] = reactive([])
function role() {
   let data = {
      _gp: 'admin.role',
      _mt: 'options'
   }
   get(data).then(res => {
      let { errno, data } = res
      if (200 === errno) {
         options = data
      }
   })
}
onMounted(() => {
   init()//渲染管理员
   role()//角色权限
})
// 渲染角色权限的内容
function handlerole(item:number) {
   for (const s of options) {
      if (s.value == item) {
         return s.label
      }
   }
   return ""
}
// 查找
function handSearch() {
   if (tableData.value.length==0) {
      ElMessage.error('没有查找到')
      
   } else {
     init()
   }
  
}
// 添加
const dialogFormVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const formLabelWidth = '80px'
const rules = reactive({//弹出框的表单非空验证
   username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],

   password: [{ required: true, message: '密码不能为空', trigger: 'blur' },
   {pattern:/^(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9~!@&%#_]{3,10}$/,message:'必须包含一个大写，一个小写字母，且长度为1到10位'}],

   phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' },
   { pattern: /^(1[0-9])\d{9}$/, message: '手机号格式不正确'}],

   realname: [{ required: true, message: '真实姓名不能为空' },{pattern:/^[\u4e00-\u9fa5]{2,10}$/,message:'2-10个汉字'}],
})
let bool = ref(false)//标记
const form = reactive({//添加请求数据
   data:new ClassAdminUser()
})
function add() {//添加弹出框
   dialogFormVisible.value = true
   bool.value = true
   form.data=new ClassAdminUser()//添加完成重新赋值为空
}
function handleUpdata($index: number, row: ClassAdminUser) {//编辑弹出框
   bool.value = false
   dialogFormVisible.value = true
   Object.assign(form.data,row)//浅拷贝
}
// 表单验证与添加编辑
function handleToggleConfirm(formEl: FormInstance | undefined) {
   if (!formEl) return
   formEl.validate((valid) => {
      if (valid) {
         let data = {//添加与编辑请求数据
            _gp: 'admin',
            _mt: bool.value == true ? 'create' : 'edit',
            adminDTO: JSON.stringify(form.data)
         }
         post(data).then(res => {
            let { errno, errmsg } = res
            if (200 === errno) {
               dialogFormVisible.value = false
               init()
            } else {
               ElMessage.error(errmsg)
            }
         })
      } else {
         return false
      }
   })

}
// 删除一行
function handleDelete($index: number, id: number) {
   ElMessageBox.confirm(
    '确定删除吗?',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    }
  ).then(()=>{
   let dataDelete = { _gp: 'admin', _mt: 'delete', id }
   post(dataDelete).then(res => {
      let { errno, errmsg } = res
      200 === errno ? init() : ElMessage.error(errmsg)
   })
  })
   
}

// 分页
function CurrentList(v: PagingType) {
   console.log(v);
   
   list.value.page = v.pageNo
   list.value.limit = v.pageSize
   init()
}
// 重置
const ruset= (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scoped>
.input-length {
   width: 300px;
   margin-right: 10px;
}
</style>